package com.yanqu.road.server.manager.mogulbirthday;

import com.yanqu.road.dao.impl.mogulbirthday.MogulBirthDayConfigDaoImpl;
import com.yanqu.road.entity.mogulbirthday.MogulBirthDayInfo;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.pb.bossbirthday.MogulBirthdayProto;
import com.yanqu.road.server.TempCrossMgr;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.user.CrossUserMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.date.DateHelper;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class MogulBirthdayMgr extends TempCrossMgr {

    //玩家最高称号
    private static Map<Long, Integer>  bestDecorationMap = new ConcurrentHashMap<>();

    //date 1101
    private static Map<Integer, Map<Long, MogulBirthDayInfo>> dataMap;

    @Override
    public boolean removeExpireData() throws Exception {
        return true;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        List<MogulBirthDayInfo> list = new MogulBirthDayConfigDaoImpl().getMogulBirthDayInfoList();
        Map<Integer, Map<Long, MogulBirthDayInfo>> tempMap = new ConcurrentHashMap<>();
        Calendar calendar = Calendar.getInstance();
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        Calendar tempCalendar = Calendar.getInstance();
        for (MogulBirthDayInfo dayInfo : list) {
            tempCalendar.setTime(dayInfo.getBirthDay());
            if(tempCalendar.get(Calendar.MONTH) >= month && tempCalendar.get(Calendar.DAY_OF_MONTH) >= day){
                int monthDay = getMonthDay(tempCalendar);
                if(!tempMap.containsKey(monthDay)){
                    tempMap.put(monthDay, new HashMap<>());
                }
                tempMap.get(monthDay).put(dayInfo.getUserId(), dayInfo);
            }
        }
        dataMap = tempMap;
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    public static void syncData(long serverId, long playerId, MogulBirthdayProto.CrossMogulBirthdaySyncData syncData) {
        Calendar calendar = Calendar.getInstance();
        int monthDay = getMonthDay(calendar);
        MogulBirthdayProto.MogulBirthdaySyncData.Builder syncDataBuilder = MogulBirthdayProto.MogulBirthdaySyncData.newBuilder();
        MogulBirthDayInfo myDayInfo = null;
        Map<Long, MogulBirthDayInfo> todayMap = dataMap.get(monthDay);
        if(todayMap != null){
            myDayInfo = todayMap.get(playerId);
            for (Map.Entry<Long, MogulBirthDayInfo> infoEntry : todayMap.entrySet()) {
                if(infoEntry.getKey() == playerId || (syncData.hasUserData() && syncData.getUserIdList().contains(infoEntry.getKey()))){
                    continue;
                }
                if(!infoEntry.getValue().getPosterServerList().contains(serverId)){
                    continue;
                }
                MogulBirthdayProto.MogulBirthdayPosterTemp.Builder posterBuilder = MogulBirthdayProto.MogulBirthdayPosterTemp.newBuilder();
                posterBuilder.setUserId(infoEntry.getKey());
                posterBuilder.setBlessReward(infoEntry.getValue().getBlessReward());
                posterBuilder.setRemark(infoEntry.getValue().getRemark());
                posterBuilder.setChengHao(bestDecorationMap.getOrDefault(infoEntry.getKey(), 0));

                UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(infoEntry.getKey());
                if(userBaseInfo != null){
                    posterBuilder.setPlayer(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
                }
                //海报
                syncDataBuilder.addPoster(posterBuilder);
            }
        }
        //今日是生辰，才下发 userData
        if(myDayInfo != null){
            MogulBirthdayProto.MogulBirthdayUserDataTemp.Builder userDataBuilder;
            if(syncData.hasUserData()){
                userDataBuilder = syncData.getUserData().toBuilder();
            }else {
                userDataBuilder = MogulBirthdayProto.MogulBirthdayUserDataTemp.newBuilder();
                userDataBuilder.setGetReward(false);
            }
            userDataBuilder.setBirthday(DateHelper.getZeroTime((int)(myDayInfo.getBirthDay().getTime() / 1000)));
            userDataBuilder.setReward(myDayInfo.getReward());
            syncDataBuilder.setUserData(userDataBuilder);
        }
        MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(Protocol.U_MOGUL_BIRTHDAY_SYNC_DATA, syncDataBuilder));
    }

    public static void getPosterReward(long serverId, long playerId, long userId, long today){
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(today * 1000);
        int monthDay = getMonthDay(calendar);

        MogulBirthdayProto.MogulBirthdayPosterGetRewardRespMsg.Builder respMsg = MogulBirthdayProto.MogulBirthdayPosterGetRewardRespMsg.newBuilder();
        respMsg.setMogulId(userId);
        respMsg.setRet(GameErrorCode.E_MOGUL_BIRTHDAY_TODAY_NO_REWARD);
        MogulBirthDayInfo birthDayInfo = null;
        if(dataMap.containsKey(monthDay)){
            Map<Long, MogulBirthDayInfo> todayMap = dataMap.get(monthDay);
            birthDayInfo = todayMap.get(userId);
            if(birthDayInfo != null){
                respMsg.setRet(0);
                respMsg.setReward(birthDayInfo.getBlessReward());
            }
        }

        if(respMsg.getRet() == 0 && birthDayInfo != null){
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(Protocol.S_MOGUL_BIRTHDAY_POSTER_GET_REWARD_FROM_CROSS, respMsg));

            //统计領取数量
            MogulBirthdayProto.MogulBirthdayPosterGetNumSync.Builder numSync = MogulBirthdayProto.MogulBirthdayPosterGetNumSync.newBuilder();
            numSync.setUserId(birthDayInfo.getUserId());
            numSync.setToday(today);
            MessageHelper.sendPacket(birthDayInfo.getServerId(), 0, YanQuMessageUtils.buildMessage(Protocol.S_MOGUL_BIRTHDAY_POSTER_GET_REWARD_STAT_FROM_CROSS, numSync));
        }else {
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(Protocol.U_MOGUL_BIRTHDAY_POSTER_GET_REWARD, respMsg));
        }
    }

    public static int getMonthDay(Calendar calendar){
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int monthDay = Integer.valueOf(month + (day > 9 ? "": "0") + day);
        return monthDay;
    }

    /**
     * 領取生辰奖励
     */
    public static void getMyReward(long serverId, long playerId, long today) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(today * 1000);
        int monthDay = getMonthDay(calendar);

        MogulBirthdayProto.CrossMogulBirthdayUserGetRewardRespMsg.Builder crossResp = MogulBirthdayProto.CrossMogulBirthdayUserGetRewardRespMsg.newBuilder();
        crossResp.setToday(today);
        crossResp.setRet(GameErrorCode.E_MOGUL_BIRTHDAY_TODAY_NO_REWARD);
        MogulBirthDayInfo birthDayInfo = null;
        if(dataMap.containsKey(monthDay)){
            Map<Long, MogulBirthDayInfo> todayMap = dataMap.get(monthDay);
            birthDayInfo = todayMap.get(playerId);
            if(birthDayInfo != null){
                if(birthDayInfo.isGetUserReward()){
                    crossResp.setRet(GameErrorCode.E_MOGUL_BIRTHDAY_USER_REWARD_GOT);
                }else {
                    crossResp.setRet(0);
                    crossResp.setReward(birthDayInfo.getReward());
                    crossResp.setToday(today);
                    crossResp.setBirthday(birthDayInfo.getBirthDay().getTime() / 1000);
                    crossResp.addAllServerId(birthDayInfo.getBanquetServerList());
                    birthDayInfo.setGetUserReward(true);
                }
            }
        }

        if(crossResp.getRet() == 0 && birthDayInfo != null){
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(Protocol.S_MOGUL_BIRTHDAY_USER_GET_REWARD_FROM_CROSS, crossResp));

        }else {
            MogulBirthdayProto.MogulBirthdayUserGetRewardRespMsg.Builder respMsg = MogulBirthdayProto.MogulBirthdayUserGetRewardRespMsg.newBuilder();
            respMsg.setRet(crossResp.getRet());
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(Protocol.U_MOGUL_BIRTHDAY_USER_GET_REWARD, respMsg));
        }
    }

    public static void fetchMogulDecoration(){
        Calendar calendar = Calendar.getInstance();
        int todayDay = getMonthDay(calendar);
        calendar.add(Calendar.DATE, 1);
        int tomorrow = getMonthDay(calendar);
        int[] days = new int[]{todayDay, tomorrow};
        Map<Long, List<Long>> serverUserMap = new HashMap<>();
        for (int day : days) {
            Map<Long, MogulBirthDayInfo> map = dataMap.get(day);
            if(map == null){
                continue;
            }
            for (Map.Entry<Long, MogulBirthDayInfo> entry : map.entrySet()) {
                if(bestDecorationMap.containsKey(entry.getKey())){
                    continue;
                }
                long serverId = getUserServerId(entry.getKey());
                if(!serverUserMap.containsKey(serverId)){
                    serverUserMap.put(serverId, new ArrayList<>());
                }
                serverUserMap.get(serverId).add(entry.getKey());
            }
        }
        for (Map.Entry<Long, List<Long>> entry : serverUserMap.entrySet()) {
            MogulBirthdayProto.MogulBirthdayUploadBestDecorationReqMsg.Builder builder = MogulBirthdayProto.MogulBirthdayUploadBestDecorationReqMsg.newBuilder();
            builder.addAllUserId(entry.getValue());
            MessageHelper.sendPacket(entry.getKey(), 0, YanQuMessageUtils.buildMessage(Protocol.S_MOGUL_BIRTHDAY_BEST_DECORATION_FETCH, builder));
        }
    }

    public static long getUserServerId(long userId){
        long userServerId = 0;
        try {
            userServerId = Long.parseLong(String.valueOf(userId).substring(0, 8));
        }catch (Exception e){
            getLogger().info("userId {} exception", userId);
        }
        return userServerId;
    }

    public static Map<Long, Integer> getBestDecorationMap() {
        return bestDecorationMap;
    }

    public static Map<Integer, Map<Long, MogulBirthDayInfo>> getDataMap() {
        return dataMap;
    }
}
